﻿using System.Collections.Generic;
using System.Threading.Tasks;

namespace RockBus.Threading
{
    public static class TaskExtensions
    {
        /// <summary>
        /// Returns a completed Task with the specified result type set to null.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="taskFactory"></param>
        /// <returns></returns>
        public static Task<T> NullResult<T>(this TaskFactory taskFactory)
            where T : class
        {
            var emptyCompletedTcs = new TaskCompletionSource<T>();
            emptyCompletedTcs.SetResult(null);
            return emptyCompletedTcs.Task;
        }

        public static bool IsFinished(this Task task)
        {
            return ((task.Status == TaskStatus.Canceled) ||
                    (task.Status == TaskStatus.Faulted) ||
                    (task.Status == TaskStatus.RanToCompletion));
        }

        public static bool WaitAll(int milliseconds, params Task[] tasks)
        {
            return Task.WaitAll(tasks, milliseconds);
        }

        public static IEnumerable<TaskStatus> WaitForTaskStatusses(params Task[] tasks)
        {
            foreach (var task in tasks)
            {
                yield return task.WaitForCompletionStatus();
            }
        }
    }
}